/*
 * @Author: your name
 * @Date: 2019-08-08 20:43:58
 * @LastEditTime: 2020-12-23 16:10:03
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \egg-RESTfulAPI\app\extend\helper.js
 */
const moment = require('moment')

// 格式化时间
exports.formatTime = time => moment(time).format('YYYY-MM-DD hh:mm:ss')

// 处理成功响应
exports.success = ({ ctx, res = null, msg = '请求成功' }) => {
  ctx.body = {
    code: 0,
    data: res,
    msg
  }
  ctx.status = 200
}
exports.Unprocesable = ({ ctx, res = null, msg = '验证错误' }) => {
  ctx.body = {
    msg
  }
  ctx.status = 422
}
exports.InvaidRequest = ({ ctx, res = null, msg = '验证错误' }) => {
  ctx.body = {
    msg
  }
  ctx.status = 400
}


exports.pile = ({ ctx, data }) => {
  let { app } = ctx

  ctx.body = {
    ...data
  }
  ctx.status = 200
}

exports.pileEn = ({ ctx, OperatorID, data, result }) => {
  let { app } = ctx

  console.log(data)
  data = JSON.stringify(data)
  // console.log(data)
  let out = Buffer.from(data)
  let iv = app.config.crypto.iv
  let key = app.config.crypto.key
  let hmac = app.config.crypto.hmac
  let Data = app.context.encrypt(key, iv, out)
  let TimeStamp = moment().format('YYYYMMDDHHmmss')
  let Seq = '0001'
  let StringData = OperatorID + Data + TimeStamp + Seq
  let Sig = app.context.hmac(StringData, hmac)
  if (result == 4004) {
    ctx.body = {
      Ret: '4004',
      Msg: '业务参数不合法',
      Data: Data,
      Sig: Sig,
    }
  } else if (result == 4001) {
    ctx.body = {
      Ret: '4001',
      Msg: '签名错误',
      Data: Data,
      Sig: Sig,
    }
  } else if (result == 4002) {
    ctx.body = {
      Ret: '4002',
      Msg: 'Token错误',
      Data: Data,
      Sig: Sig,
    }
  }
  else {
    ctx.body = {
      Ret: '0',
      Msg: '请求成功',
      Data: Data,
      Sig: Sig,
    }
  }
  console.log(ctx.body)
  ctx.status = 200
}
